package com.example.administrator.qimo3no74;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.bottomnavigation.LabelVisibilityMode;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.qimo3no74.fragment.CategoryFragment;
import com.example.administrator.qimo3no74.fragment.HomeFragment;
import com.example.administrator.qimo3no74.fragment.MyFragment;
import com.example.administrator.qimo3no74.fragment.ShoppingCartFragment;

import java.lang.reflect.Method;

public class MainActivity extends AppCompatActivity {
    private Integer index = 1;
    private Toolbar toolbar;
    private TextView toolbarTitle;
    private FrameLayout frameLayout ;


    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    index = 1;
                    replaceFragment(new HomeFragment());
                    return true;
                case R.id.navigation_category:
                    index = 2;
                    replaceFragment(new CategoryFragment());
                    return true;
                case R.id.navigation_shopping_cart:
                    index = 3;
                    replaceFragment(new ShoppingCartFragment());
                    return true;
                case R.id.navigation_my:
                    index = 4;
                    replaceFragment(new MyFragment());
                    return true;
            }
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //初始化
        toolbar = findViewById(R.id.toolbar);
        toolbarTitle=toolbar.findViewById(R.id.toolbar_title);

        //fragment设置
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        navigation.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED);
        replaceFragment(new HomeFragment());


        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id){
            case  R.id.menu_share :
                Toast.makeText(this,"分享",Toast.LENGTH_SHORT).show();
                break;
            case  R.id.menu_favorite :
                Toast.makeText(this,"收藏夹",Toast.LENGTH_SHORT).show();
                break;
            case  R.id.menu_messages:
                Toast.makeText(this,"信息通知",Toast.LENGTH_SHORT).show();
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    // 让菜单同时显示图标和文字
    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (menu != null) {
            if (menu.getClass().getSimpleName().equalsIgnoreCase("MenuBuilder")) {
                try {
                    Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                    method.setAccessible(true);
                    method.invoke(menu, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return super.onMenuOpened(featureId, menu);
    }

    private void replaceFragment(Fragment fragment){
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.frameLayout,fragment);
        fragmentTransaction.commit();
        //添加toolbar
        addToolbar();
    }


    private void addToolbar(){
        switch (index){
            case 1:
                toolbar.setNavigationIcon(R.drawable.ic_sao);
                toolbar.setTitle("");
                toolbarTitle.setText("小宁商城");
                toolbar.inflateMenu(R.menu.menu_main);//设置右上角的填充菜单
                setSupportActionBar(toolbar);
                toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(v.getContext(),"扫一扫",Toast.LENGTH_SHORT).show();
                    }
                });
                break;
            case 2:
                toolbar.setNavigationIcon(null);
                toolbar.setTitle("");
                toolbarTitle.setText("分类");
                toolbar.inflateMenu(R.menu.menu_main);//设置右上角的填充菜单
                setSupportActionBar(toolbar);
                break;
            case 3:
                toolbar.setNavigationIcon(R.drawable.ic_manage);
                toolbar.setTitle("");
                toolbarTitle.setText("购物车");
                toolbar.inflateMenu(R.menu.menu_main);//设置右上角的填充菜单
                setSupportActionBar(toolbar);
                toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(v.getContext(),"管理",Toast.LENGTH_SHORT).show();
                    }
                });
                break;
            case 4:
                toolbar.setNavigationIcon(R.drawable.ic_set);
                toolbar.setTitle("");
                toolbarTitle.setText("我的");
                setSupportActionBar(toolbar);
                toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(v.getContext(),"设置",Toast.LENGTH_SHORT).show();
                    }
                });
                break;

        }

    }


    public boolean isClickEt(View view, MotionEvent event) {
        if (view != null && (view instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            // 获取输入框当前的location位置
            view.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            // 此处根据输入框左上位置和宽高获得右下位置
            int bottom = top + view.getHeight();
            int right = left + view.getWidth();
            if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            if (isClickEt(view, event)) {
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (inputMethodManager != null) {
                    // 隐藏键盘
                    inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(event);
        }
/**
 * 看源码可知superDispatchTouchEvent 是个抽象方法，用于自定义的Window
 * 此处目的是为了继续将事件由dispatchTouchEvent(MotionEvent
 * event)传递到onTouchEvent(MotionEvent event) 必不可少，否则所有组件都不能触发
 * onTouchEvent(MotionEvent event)
 */
        if (getWindow().superDispatchTouchEvent(event)) {
            return true;
        }
        return onTouchEvent(event);
    }



}
